﻿using SCM.Common;
using SCM.Common.Extensions;
using SCM.Model;
using SCM.Model.DBEntity;
using SCM.Servie.IBusiness;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace SCM.Servie.Business 
{
    /// <summary>
    /// 测试报告服务
    /// </summary>
    public class TestReportService : ITestReportService
    {
        private readonly DbContext dal = new DbContext();

        public string Add(T_TestReport model)
        {
            return dal.Insertable(model).ExecuteReturnEntity().ID;
        }

        public bool Delete(List<string> ids)
        {
            return dal.Updateable<T_TestReport>(new
            {
                DataStatus = DataStatusEnum.Deleted,
                ModifyTime = DateTime.Now,
            }).Where(p => ids.Contains(p.ID)).ExecuteCommand() > 0;
        }

        public T_TestReport GetById(string id)
        {
            return dal.Get<T_TestReport>(id);
        }

        public List<T_TestReport> GetList(string companyID)
        {
            Expression<Func<T_TestReport, bool>> whereExp = (a) => a.DataStatus == DataStatusEnum.Valid;
            if (!string.IsNullOrWhiteSpace(companyID))
            {
                whereExp = whereExp.Compose((a) => a.CompanyID == companyID, Expression.AndAlso);
            }
            return dal.Queryable<T_TestReport>().Where(whereExp).ToList();
        }

        public PageData<T_TestReport> Query(string companyID, string testReportNo, string testName, PageInfo page)
        {
            int count = 0;
            Expression<Func<T_TestReport, bool>> whereExp = (a) => a.DataStatus == DataStatusEnum.Valid;
            if (!string.IsNullOrWhiteSpace(companyID))
            {
                whereExp = whereExp.Compose((a) => a.CompanyID == companyID, Expression.AndAlso);
            }
            if (!string.IsNullOrWhiteSpace(testReportNo))
            {
                whereExp = whereExp.Compose((a) => a.TestReportNo.StartsWith(testReportNo), Expression.AndAlso);
            }
            if (!string.IsNullOrWhiteSpace(testName))
            {
                whereExp = whereExp.Compose((a) => a.TestName.StartsWith(testName), Expression.AndAlso);
            }

            List<T_TestReport> list = dal.Queryable<T_TestReport>().Where(whereExp).OrderBy(a => a.CreateTime, SqlSugar.OrderByType.Desc).ToPageList(page.PageIndex, page.PageSize, ref count);
            page.DataCount = count;
            return new PageData<T_TestReport> { Data = list, Page = page };
        }

        public bool Update(T_TestReport model)
        {
            return dal.Modify(model);
        }
    }
}
